package com.example.casper.Experiment2024.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.example.casper.Experiment2024.R;

import java.util.ArrayList;

public class WhackAMoleView extends SurfaceView implements Runnable {
    private Thread gameThread;
    private volatile boolean isPlaying;
    private SurfaceHolder surfaceHolder;
    private Paint paint;
    private int score;
    private ArrayList<Spiriter> spiriters;
    private float markerX;
    private float markerY;
    private Bitmap markerBitmap;
    private long startTime; // 计时开始时间

    public WhackAMoleView(Context context) {
        super(context);
        surfaceHolder = getHolder();
        paint = new Paint();
        score = 0;
        initMarker();
        startTime = SystemClock.elapsedRealtime(); // 记录开始时间
    }

    public WhackAMoleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        surfaceHolder = getHolder();
        paint = new Paint();
        score = 0;
        initMarker();
        startTime = SystemClock.elapsedRealtime(); // 记录开始时间
    }

    private void initMarker() {
        markerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.marine); // 假设marker图片已放在drawable文件夹下
        markerX = getWidth() / 2; // 初始位置为屏幕中央
        markerY = 1500; // 初始位置在屏幕底部上方一定距离
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                markerX = event.getX(); // 更新marker的X坐标
                break;
            case MotionEvent.ACTION_UP:
                // Do nothing on action up
                break;
        }
        return true;
    }

    @Override
    public void run() {
        spiriters = new ArrayList<>();
        for (int i = 0; i < 10; ++i) {
            spiriters.add(new Spiriter());
        }
        while (isPlaying) {
            update();
            draw();
            control();
        }
    }

    private void update() {
        for (Spiriter spiriter : spiriters) {
            spiriter.move();
            // 检查是否碰到marker，碰到则游戏暂停
            if (Math.abs(spiriter.x - markerX) < markerBitmap.getWidth() / 2 &&
                    Math.abs(spiriter.y - markerY) < markerBitmap.getHeight() / 2) {
                isPlaying = false; // 停止游戏循环
            }
            if (!spiriter.isDead && spiriter.y > markerY) {
                score++;
                spiriter.isDead = true;
            }
        }
    }

    private void draw() {
        if (surfaceHolder.getSurface().isValid()) {
            Canvas canvas = surfaceHolder.lockCanvas();
            canvas.drawColor(Color.WHITE);
            paint.setColor(Color.BLACK);
            paint.setTextSize(50);

            // 绘制得分
            canvas.drawText("Score: " + score, 50, 50, paint);

            // 绘制计时
            long elapsedTime = SystemClock.elapsedRealtime() - startTime;
            String timeString = formatTime(elapsedTime);
            canvas.drawText("Time: " + timeString, 50, 100, paint);

            // 绘制marker
            canvas.drawBitmap(markerBitmap, markerX, markerY, paint);

            // 绘制地鼠
            for (Spiriter spiriter : spiriters) {
                spiriter.draw(canvas, paint);
            }
            surfaceHolder.unlockCanvasAndPost(canvas);
        }
    }

    private void control() {
        try {
            Thread.sleep(17); // 控制帧率
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause() {
        isPlaying = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void resume() {
        isPlaying = true;
        gameThread = new Thread(this);
        gameThread.start();
    }

    private class Spiriter {
        double x, y;
        double yDelta;
        boolean isDead;

        public Spiriter() {
            yDelta = Math.random() * 10; // 只允许向下移动
            x = getWidth() * Math.random();
            y = markerBitmap.getHeight(); // 初始位置在marker下方
            isDead = false;
        }

        public void move() {
            y += yDelta;

            if (y >= getHeight()) {
                y = -markerBitmap.getHeight(); // 如果超出屏幕，则重置位置
                x = getWidth() * Math.random(); // 随机生成新位置
                isDead = false; // 重置状态
            }
        }

        public void draw(Canvas canvas, Paint paint) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bomb);
            canvas.drawBitmap(bitmap, (float) x, (float) y, paint);
        }
    }

    // 格式化时间为 mm:ss 格式
    private String formatTime(long millis) {
        int seconds = (int) (millis / 1000) % 60;
        int minutes = (int) (millis / 1000) / 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
}